from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from django.conf import settings
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializer import OauthSerializer


class OauthQQ_URLView(APIView):
    """
        构建QQ登录跳转链接
    """
    def get(self, request):
        # 1. 获取next值付给state
        state = request.query_params.get("next")

        if not state:
            state = "/"

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        login_url = oauth.get_qq_url()
        return Response({'login_url': login_url})


class OauthQQView(CreateAPIView):
    """
        获取openid
    """
    serializer_class = OauthSerializer

    # 获取 code
    def get(self, request):
        # 1、后端获取到code值请求qq服务器获取access_token值
        code = request.query_params.get('code')
        # 2、判断code值是否能够获取到
        if code is None:
            return Response({"errors": '缺少code值'}, status=403)

        # 3、借助qqSDK创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')

        access_token = qq.get_access_token(code)
        # 4、获取到access_token值请求qq服务器获取openid值
        open_id = qq.get_open_id(access_token)

        try:
            qq_user = OAuthQQUser.objects.filter(openid=open_id).get()
        except:
            from itsdangerous import TimedJSONWebSignatureSerializer as TJS
            # 　未绑定　为openid 加密
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({"openid": open_id}).decode()

            return Response({"access_token": openid})
        else:
            # 　已绑定　获取　userid,openid,username
            user = qq_user.user
            # 生成JWT token值,自己生成token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                "user_id": user.id,
                "username": user.username,
                "token": token,
            })
